package com.me.study.designPatterns.Singleton;

import com.me.common.util.SleepUtil;

import java.util.concurrent.CyclicBarrier;

/**
 * 懒汉单例: 静态内部类，通过类加载机制保证了实例只有一个
 *
 * @author ME
 * @date   2019/6/24
 */
public class StaticInnerClassSingleton {

    private static class SingletonHolder {
        private static final StaticInnerClassSingleton INSTANCE = new StaticInnerClassSingleton();
    }

    private StaticInnerClassSingleton() {
        System.out.println("实例化了。。。");
    }

    public static StaticInnerClassSingleton getInstance() {
        return SingletonHolder.INSTANCE;
    }

    public static void main(String[] args) {
        /** 增加虚拟机参数 -verbose:class 打印类加载信息。
         *  可以看到 SingletonHolder 没有直接加载，使用时才加载的
         */
        SleepUtil.seconds(3);
        System.out.println("sleep 3\n");

        int count = 1000;
        CyclicBarrier barrier = new CyclicBarrier(count);
        for (int i = 0; i < count; i++) {
            new Thread(() -> {
                try {
                    barrier.await();
                    StaticInnerClassSingleton.getInstance();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }, Integer.toString(i)).start();
        }
        SleepUtil.seconds(5);
    }
}
